﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartProduction.Domain.客户管理;
using SmartProduction.ErrorCode;
using SmartProduction.Read.API.Application.Commands.ClientInfoCommand;
using SmartProduction.Read.API.Application.Commands.IndustryCommand;
using SmartProduction.Read.API.Application.Commands.ClientInfoCommands;
using SmartProduction.Read.API.Application.Commands.MaterialInfoCommand;
using SmartProduction.Read.API.Application.Commands.ResourceUnitCommand;
using SmartProduction.Read.API.Dtos;
using ClientInfoQueryCommand = SmartProduction.Read.API.Application.Commands.ClientInfoCommands.ClientInfoQueryCommand;
using SmartProduction.Read.API.Application.Commands.ResourceInfoCommand;
using SmartProduction.Read.API.Application.Commands.SalesOrderCommand;
using SmartProduction.Read.API.Application.Commands.Export;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SmartProduction.Domain.客户管理.WorkOrder;
using SmartProduction.Read.API.Application.Commands.work_SalesOrderCommand;
using SmartProduction.Read.API.Application.Commands.Work_CaigouOrderCommand;

namespace SmartProduction.Read.API.Controllers
{
    /// <summary>
    /// API控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ResourceController : ControllerBase
    {

        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mediator">中介者</param>
        public ResourceController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        /// <summary>
        /// 获取资源单位表
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public async Task<APIResult<List<ResourceUnit>>> GetResourceUnit([FromQuery]ResourceUnitQueryCommand command)
        {
            try
            {
                return await mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取客户行业信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public Task<APIResult<List<Industry>>> GetIndustry([FromQuery]IndustryQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// <summary>
        /// 获取客户行业信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public Task<APIResult<APIPaing<ClientInfoDTO>>> GetClient([FromQuery]ClientInfoQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取资源列表信息
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public Task<APIResult<APIPaing<ResourceDTO>>> GetResourceInfo([FromQuery]ResourceInfoQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 销售订单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Task<APIResult<APIPaing<SalesOrder>>> SalesOrderList([FromQuery]SalesOrderQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 物料服务列表
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回任务</returns>
        [HttpGet]
        public Task<APIResult<APIPaing<MaterialInfo>>> MaterialList([FromQuery]MaterialInfoQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <returns>返回</returns>
        [HttpGet]
        public Task<APIResult<List<ExportClientCommandityDTO>>> ExportClient([FromQuery]ExportClientCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="ClientInfoId">客户id</param>
        /// <returns>返回</returns>
        [HttpGet]
        public async Task<IActionResult> ExportClientInfo([FromQuery] List<int> ClientInfoId)
        {
            try
            {
                if (ClientInfoId == null || !ClientInfoId.Any())
                {
                    return BadRequest("请提供产品ID列表");
                }

                var request = new ExportClientCommand { ClientInfoId = ClientInfoId };
                var result = await ExportClient(request);

                if (result.data?.Any() != true)
                    return NotFound("未找到产品数据");

                using IWorkbook book = new XSSFWorkbook();
                ISheet sheet = book.CreateSheet("产品列表");
                IRow heardRow = sheet.CreateRow(0);

                //设置表头
                string[] headers = { "", "客户编码", "客户名称", "客户区分", "客户电话", "客户邮箱", "客户地址", "所在国家", "所在城市" };
                for (int i = 0; i < headers.Length; i++)
                    heardRow.CreateCell(i).SetCellValue(headers[i]);

                //填充数据行
                int rowIndex = 1;
                foreach (var item in result.data)
                {
                    IRow row = sheet.CreateRow(rowIndex++);
                    row.CreateCell(1).SetCellValue(item.ClientInfoNumer);
                    row.CreateCell(2).SetCellValue(item.ClientInfoName);
                    row.CreateCell(3).SetCellValue(item.ClientInfoPhone);
                    row.CreateCell(4).SetCellValue(item.ClientInfoEmail);
                    row.CreateCell(5).SetCellValue(item.ClientInfoType);
                    row.CreateCell(6).SetCellValue(item.ClientInfoAddr);
                    row.CreateCell(7).SetCellValue(item.CountryName);
                    row.CreateCell(8).SetCellValue(item.CountryCity);
                }

                using var ms = new MemoryStream();
                book.Write(ms);
                byte[] buffer = ms.ToArray();

                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ", "客户信息导出列表.xlsx");
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 导出列表查询
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<APIResult<List<ExportSalesOrderCommandityDTO>>> ExportSales([FromQuery]ExportSalesOrderCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
           
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="SalesOrderId">销售订单id</param>
        /// <returns>返回</returns>
        [HttpGet]
        public async Task<IActionResult> ExportSalesOrder([FromQuery] List<int> SalesOrderId)
        {
            try
            {
                if (SalesOrderId == null || !SalesOrderId.Any())
                {
                    return BadRequest("请提供销售订单列表ID");
                }

                var request = new ExportSalesOrderCommand { SalesOrderId = SalesOrderId };
                var result = await ExportSales(request);

                if (result.data?.Any() != true)
                    return NotFound("未找到销售订单数据");

                using IWorkbook book = new XSSFWorkbook();
                ISheet sheet = book.CreateSheet("销售订单列表");
                IRow heardRow = sheet.CreateRow(0);

                //设置表头
                string[] headers = { "", "订单编码", "订单名称", "订单类型", "所属项目", "订单金额", "币种", "计税类型", "税率", "开票金额(含税)", "已收款金额(含税)", "销售员", "销售部门" };
                for (int i = 0; i < headers.Length; i++)
                    heardRow.CreateCell(i).SetCellValue(headers[i]);

                //填充数据行
                int rowIndex = 1;
                foreach (var item in result.data)
                {
                    IRow row = sheet.CreateRow(rowIndex++);
                    row.CreateCell(1).SetCellValue(item.SalesOrderNumer);
                    row.CreateCell(2).SetCellValue(item.ClientInfoNumer);
                    row.CreateCell(3).SetCellValue(item.SalesOrderType);
                    row.CreateCell(4).SetCellValue(item.AltEnter);
                    row.CreateCell(5).SetCellValue(item.SalesOrderPrice);
                    row.CreateCell(6).SetCellValue(item.Currency);
                    row.CreateCell(7).SetCellValue(item.TaxType);
                    row.CreateCell(8).SetCellValue(item.Taxrate);
                    row.CreateCell(9).SetCellValue(item.InvoicePrice);
                    row.CreateCell(10).SetCellValue(item.AmountPrice);
                    row.CreateCell(11).SetCellValue(item.SalesMan);
                    row.CreateCell(12).SetCellValue(item.SalesDepart);
                }

                using var ms = new MemoryStream();
                book.Write(ms);
                byte[] buffer = ms.ToArray();

                return File(buffer, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "销售订单导出列表.xlsx");
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 销售订单列表
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpGet]
        public Task<APIResult<APIPaing<work_SalesOrder>>> workSalesOrderList([FromQuery]work_SalesOrderQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 采购订单列表
        /// </summary>
        /// <param name="command">命令</param>
        /// <returns>返回</returns>
        [HttpGet]
        public Task<APIResult<APIPaing<Work_CaigouOrder>>> workCaigouOrderList([FromQuery]Work_CaigouOrderQueryCommand command)
        {
            try
            {
                return mediator.Send(command);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
